package models

import (
	"github.com/beego/beego/v2/client/orm"
)

// Member 会员模型
type Member struct {
	BaseModel
	Name            string  `orm:"size(50)" json:"name"`
	MemberNo        string  `orm:"size(20);unique" json:"member_no"`
	Phone           string  `orm:"size(20);" json:"phone"`
	Avatar          string  `orm:"size(255)" json:"avatar"`
	Gender          int8    `orm:"default(0)" json:"gender"`                    // 0:未知, 1:男, 2:女
	Birthday        int64   `orm:"default(0)" json:"birthday"`                  // 生日，时间戳
	Password        string  `orm:"size(64)" json:"password"`                    // 加密后的密码
	Salt            string  `orm:"size(32)" json:"salt"`                        // 密码盐
	OpenId          string  `orm:"size(64)" json:"open_id"`                     // 微信OpenID
	UnionId         string  `orm:"size(64)" json:"union_id"`                    // 微信UnionID
	Balance         float64 `orm:"digits(10);decimals(2)" json:"balance"`       // 账户余额
	Points          int     `orm:"default(0)" json:"points"`                    // 积分
	LevelId         int64   `orm:"default(1)" json:"level_id"`                  // 会员等级ID
	Status          int8    `orm:"default(1)" json:"status"`                    // 1:正常, 0:禁用
	LastLoginAt     int64   `orm:"default(0)" json:"last_login_at"`             // 最后登录时间
	LastLoginIp     string  `orm:"size(50)" json:"last_login_ip"`               // 最后登录IP
	RegisterIp      string  `orm:"size(50)" json:"register_ip"`                 // 注册IP
	LastConsumeTime int64   `orm:"default(0)" json:"last_consume_time"`         // 最后消费时间
	TotalConsume    float64 `orm:"digits(10);decimals(2)" json:"total_consume"` // 累计消费金额
}

// TableName 设置表名
func (m *Member) TableName() string {
	return "ss_member"
}

// GetMemberById 根据ID获取会员信息
func GetMemberById(id int64, franchiseId int64) (*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	return member, err
}

// GetMemberByPhone 根据手机号获取会员信息
func GetMemberByPhone(phone string, franchiseId int64) (*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("phone", phone).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	return member, err
}

// GetMemberByOpenId 根据OpenID获取会员信息
func GetMemberByOpenId(openId string, franchiseId int64) (*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("open_id", openId).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	return member, err
}

// GetMemberList 获取会员列表
func GetMemberList(page, pageSize int, filters map[string]interface{}) ([]*Member, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member))

	// 应用过滤条件
	if name, ok := filters["name"].(string); ok && name != "" {
		qs = qs.Filter("name__contains", name)
	}

	if phone, ok := filters["phone"].(string); ok && phone != "" {
		qs = qs.Filter("phone__contains", phone)
	}

	if levelId, ok := filters["level_id"].(int64); ok {
		qs = qs.Filter("level_id", levelId)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 加盟商过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var members []*Member
	_, err := qs.OrderBy("-id").Limit(pageSize, (page-1)*pageSize).All(&members)

	return members, total, err
}

// CreateMember 创建会员
func CreateMember(member *Member) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(member)
	return id, err
}

// GetMemberCountByLevelId 获取使用指定会员等级的会员数量
func GetMemberCountByLevelId(levelId int64, franchiseId int64) (int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("level_id", levelId).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	return qs.Count()
}

// UpdateMember 更新会员信息
func UpdateMember(member *Member, franchiseId int64, fields ...string) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("id", member.Id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	existingMember := &Member{}
	err := qs.One(existingMember)
	if err != nil {
		return err
	}

	// 确保不修改加盟商ID
	member.FranchiseId = existingMember.FranchiseId
	_, err = o.Update(member, fields...)
	return err
}

// DeleteMember 删除会员（软删除）
func DeleteMember(id int64, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	if err != nil {
		return err
	}

	member.IsDeleted = 1
	_, err = o.Update(member, "IsDeleted")
	return err
}

// UpdateMemberPoints 更新会员积分
func UpdateMemberPoints(id int64, points int, franchiseId int64) error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("id", id).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	if err != nil {
		return err
	}

	member.Points += points
	_, err = o.Update(member, "Points", "UpdatedAt")
	return err
}

// 通用会员名字获取会员信息
func GetMemberByName(name string, franchiseId int64) (*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("name", name).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	return member, err
}

// GetMembersByFilters 根据条件筛选会员
func GetMembersByFilters(filters map[string]interface{}) ([]*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member))

	// 应用过滤条件
	if level, ok := filters["level"].(int); ok && level > 0 {
		qs = qs.Filter("level", level)
	}

	if regStartTime, ok := filters["reg_start_time"].(int64); ok && regStartTime > 0 {
		qs = qs.Filter("created_at__gte", regStartTime)
	}

	if regEndTime, ok := filters["reg_end_time"].(int64); ok && regEndTime > 0 {
		qs = qs.Filter("created_at__lte", regEndTime)
	}

	// 加盟商过滤
	if franchiseId, ok := filters["franchise_id"].(int64); ok && franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	var members []*Member
	_, err := qs.All(&members)
	return members, err
}

// GetMemberCount 获取会员总数
func GetMemberCount(franchiseId int64) (int64, error) {
	o := orm.NewOrm()
	var count int64

	// 构建查询条件
	whereClause := "is_deleted = 0"
	params := []interface{}{}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND franchise_id = ?"
		params = append(params, franchiseId)
	}

	// 执行查询
	err := o.Raw("SELECT COUNT(*) FROM ss_member WHERE "+whereClause, params...).QueryRow(&count)
	return count, err
}

// GetMemberByMemberNo 根据会员号获取会员信息
func GetMemberByMemberNo(memberNo string, franchiseId int64) (*Member, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Member)).Filter("member_no", memberNo).Filter("is_deleted", 0)

	// 加盟商过滤
	if franchiseId > 0 {
		qs = qs.Filter("franchise_id", franchiseId)
	}

	member := &Member{}
	err := qs.One(member)
	return member, err
}
